﻿using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using yzrilyzr.util;

namespace FAQ_UI
{
	public class GifDrawable : Drawable, GifDecoder.Decoder
	{
		private GifDecoder.DecodedFrames frames;
		private GifDecoder.GifPlayer player;

		public GifDrawable(byte[] data)
		{
			GifDecoder decoder = new GifDecoder();
			decoder.fromByte(data);
			this.frames = decoder.getDecodedFrames(this);
			this.player = new GifDecoder.GifPlayer(this.frames);
		}

		public override void draw(DrawingContext canvas)
		{
			canvas.DrawImage((ImageSource)player.getCurrentFrame(), bounds);
			invalidateSelf();
		}
		public override double getIntrinsicWidth()
		{
			return frames.getWidth();
		}

		public override double getIntrinsicHeight()
		{
			return frames.getHeight();
		}

		public object decode(GifDecoder.GifRawFrame rawFrame, GifDecoder.DecodedFrames frames, object bg, object prev, GifDecoder.GraphicControlExtension gce, GifDecoder.GraphicControlExtension lastGce)
		{
			int disposeMethod = GifDecoder.DISPOSE_METHOD_LEAVE_IN_PLACE;
			if (lastGce != null) disposeMethod = lastGce.DisposalMethod;
			if (disposeMethod == 0) disposeMethod = 1;
			byte[] barr = rawFrame.extractImage();
			BitmapImage b = FAQUtil.loadBitmap(barr);

			if (disposeMethod == GifDecoder.DISPOSE_METHOD_LEAVE_IN_PLACE)
			{
				var drawingVisual = new DrawingVisual();
				GifDecoder.ImageBlock block = rawFrame.imageBlock;
				Rect dst = new Rect(block.Left, block.Top, block.Width, block.Height);
				Rect dst1 = new Rect(0,0, frames.getWidth(), frames.getHeight());
				using (DrawingContext dc = drawingVisual.RenderOpen())
				{
					if (bg != null) dc.DrawImage((ImageSource)bg, dst1);
					if (prev != null) dc.DrawImage((ImageSource)prev, dst1);
					dc.DrawImage(b, dst);
				}
				RenderTargetBitmap bitmap = new RenderTargetBitmap(frames.getWidth(), frames.getHeight(), 96, 96, PixelFormats.Default);
				bitmap.Render(drawingVisual);
				return bitmap;
			}
			if (disposeMethod == GifDecoder.DISPOSE_METHOD_RESTORE_TO_BG)
			{
				return b;
			}
			if (disposeMethod == GifDecoder.DISPOSE_METHOD_RESTORE_TO_PREV)
			{
				return prev;
			}
			return b;
		}
	}
}